import Router from 'koa-router'
import { User } from '../db/index.js'
import bcrypt from 'bcryptjs'

const router = new Router()

// API：注册
router.post('/sign-up', async (ctx) => {
  const body = ctx.request.body
  // 检查用户名是否被占用
  const findResult = await User.find({ username: body.username })
  if (findResult.length !== 0) {
    return ctx.rr('用户名已被占用！')
  }

  // 注册新用户
  const user = new User({
    username: body.username,
    password: bcrypt.hashSync(body.password, 10)
  })
  await user.save()
  ctx.cc()
})

// API：登录
router.post('/sign-in', async (ctx) => {
  const body = ctx.request.body
  const user = await User.findOne({ username: body.username })
  if (!user) {
    return ctx.rr('登录失败！')
  }
  const compareResult = bcrypt.compareSync(body.password, user.password)
  if (!compareResult) {
    return ctx.rr('登录失败！')
  }
  // 把用户信息存储到 session 中
  ctx.session.user = user
  // 把登录状态存到 session 中
  ctx.session.isSignIn = true
  ctx.cc()
})

// API：退出登录
router.get('/sign-out', (ctx) => {
  ctx.session = null
  ctx.redirect('/')
})

export default router
